package me.codegenerator2.utils.excel;

import me.codegenerator2.exception.BadRequestException;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.util.ReflectionUtils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhongfs
 */
public class ParseExcelDataUtil {

    public static String[] getExcelHead(InputStream inputStream) throws Exception {

        if (null == inputStream) {
            throw new RuntimeException("Empty file!");
        }
        Workbook wb = null;
        try {
            // 构造Workbook（工作薄）对
            wb = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(0);
        int rowNum = row.getLastCellNum();
        String[] tableHead = new String[rowNum];
        if (row != null) {
            Cell cell = null;
            Map<String, Object> map = new HashMap<String, Object>();
            for (int j = 0; j < rowNum; j++) {
                cell = row.getCell(j);
                if (cell != null) {
                    tableHead[j] = getCellValue(cell);
                }
            }
        }

        return tableHead;
    }

    public static String[] getExcelHead(File file) throws Exception {
        String[] tableHead = getExcelHead(new FileInputStream(file));
        return tableHead;
    }

    public static String[] getExcelHead(Workbook wb) throws Exception {
        // 构造Workbook（工作薄）对
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(0);
        int rowNum = row.getLastCellNum();
        String[] tableHead = new String[rowNum];
        if (row != null) {
            Cell cell = null;
            Map<String, Object> map = new HashMap<String, Object>();
            for (int j = 0; j < rowNum; j++) {
                cell = row.getCell(j);
                if (cell != null) {
                    tableHead[j] = getCellValue(cell);
                }
            }
        }

        return tableHead;
    }

    public static List<String> getExcelColumn(Workbook wb, int k) throws Exception {
        // 构造Workbook（工作薄）对
        Sheet sheet = wb.getSheetAt(0);
        List<String> excelColumn = new ArrayList<String>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                int rowNum = row.getLastCellNum();
                String value = null;
                String cellvalue = null;
                Cell cell = row.getCell(k);
                if (cell != null)
                //if (!cell.equals(""))
                {
                    cellvalue = getCellValue(cell);
                    if (!StringUtils.isEmpty(cellvalue)) {
                        value = cellvalue.substring(0, 7);
                    }
                }

                excelColumn.add(value);
            }
        }

        return excelColumn;
    }

    public static List<String> getExcelColumnNoSub(Workbook wb, int k) throws Exception {
        // 构造Workbook（工作薄）对
        Sheet sheet = wb.getSheetAt(0);
        List<String> excelColumn = new ArrayList<String>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                int rowNum = row.getLastCellNum();
                String value = null;
                String cellvalue = null;
                Cell cell = row.getCell(k);
                if (cell != null)
                //if (!cell.equals(""))
                {
                    cellvalue = getCellValue(cell);
                    if (!StringUtils.isEmpty(cellvalue)) {
                        value = cellvalue;
                    }
                }

                excelColumn.add(value);
            }
        }

        return excelColumn;
    }

    /**
     * @param wb
     * @param k
     * @return
     * @throws Exception
     */
    public static void CheckExcelColumnIsNull(Workbook wb, int k) throws Exception {
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null && !CheckRowIsNull(row)) {
                Cell cell = row.getCell(k);
                if (cell == null || "BLANK".equals(cell.getCellTypeEnum()) || StringUtils.isEmpty(getCellValue(cell))) {
                    throw new BadRequestException("该excel文件的第" + (k + 1) + "列存在空值！！！");
                }
            }
        }
    }

    /**
     * @param row
     * @return
     * @throws Exception
     */
    public static boolean CheckRowIsNull(Row row) throws Exception {

        if (row != null) {
            for (int i = 0; i < row.getLastCellNum(); i++) {
                Cell cell = row.getCell(i);
                if (!(cell == null || "BLANK".equals(cell.getCellTypeEnum()) || StringUtils.isEmpty(getCellValue(cell)))) {
                    return false;
                }
            }
        }
        return true;
    }


    public static List<Map<String, Object>> parseExcelFile(File file, String[] cellKeys) throws Exception {
        List<Map<String, Object>> objList = parseExcelFile(new FileInputStream(file), cellKeys);
        return objList;
    }

    /**
     * 根据Excel生成对应的对象
     *
     * @param inputStream 上传文件流
     * @param cellKeys    对应Excel的行数据,每行对应到对象的Field值
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> parseExcelFile(InputStream inputStream, String[] cellKeys) throws Exception {
        SimpleTypeConverter typeConverter = new SimpleTypeConverter();
        if (null == inputStream) {
            throw new RuntimeException("Empty file!");
        }
        if (null == cellKeys || cellKeys.length == 0) {
            throw new RuntimeException("Cell keys can't be null");
        }
        Workbook wb = null;
        try {
            // 构造Workbook（工作薄）对
            wb = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        List<Map<String, Object>> objList = new ArrayList<Map<String, Object>>();
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                int lastCellNum = Math.min(row.getLastCellNum(), cellKeys.length);
                Cell cell = null;
                Map<String, Object> map = new HashMap<String, Object>();
                for (int j = 0; j < lastCellNum; j++) {
                    cell = row.getCell(j);
                    if (!(cell == null || cell.equals(""))) {
                        map.put(cellKeys[j], getCellValue(cell));
                    }
                }
                if (!(map.isEmpty() || map == null)) {
                    objList.add(map);
                }
            }
        }
        return objList;
    }

    public static List<Map<String, Object>> parseExcelFile(Workbook wb, String[] cellKeys) throws Exception {
        if (null == cellKeys || cellKeys.length == 0) {
            throw new RuntimeException("Cell keys can't be null");
        }
        List<Map<String, Object>> objList = new ArrayList<Map<String, Object>>();
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                int lastCellNum = Math.min(row.getLastCellNum(), cellKeys.length);
                Cell cell = null;
                Map<String, Object> map = new HashMap<String, Object>();
                for (int j = 0; j < lastCellNum; j++) {
                    cell = row.getCell(j);
                    if (cell != null) {
                        String cellValue = getCellValue(cell);
                        if (!StringUtils.isBlank(cellValue)) {
                            map.put(cellKeys[j], cellValue);
                        }
                    }
                }
                if (!(map.isEmpty() || map == null)) {
                    objList.add(map);
                }
            }
        }
        return objList;
    }

    public static List<String> parseExcelFile(Workbook wb) throws Exception {

        List<String> objList = new ArrayList<String>();
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                int lastCellNum = row.getLastCellNum();
                Cell cell = null;

                for (int j = 0; j < lastCellNum; j++) {
                    cell = row.getCell(j);
                    if (!(cell == null || cell.equals(""))) {
                        String cellValue = getCellValue(cell);
                        if (!StringUtils.isBlank(cellValue)) {

                        }
                    }
                }

            }
        }
        return objList;
    }


    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellTypeEnum()) {
                // 如果当前Cell的Type为NUMERIC
                case NUMERIC: {
                    short format = cell.getCellStyle().getDataFormat();
                    //excel中的时间格式
                    if (format == 14 || format == 31 || format == 57 || format == 58) {

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = DateUtil.getJavaDate(value);
                        cellValue = sdf.format(date);
                    }
                    // 判断当前的cell是否为Date
                    //先注释日期类型的转换，在实际测试中发现HSSFDateUtil.isCellDateFormatted(cell)只识别2014/02/02这种格式。
                    else if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，取得该Cell的Date值           // 对2014-02-02格式识别不出是日期格式
                        Date date = cell.getDateCellValue();
                        cellValue = DateFormatUtils.format(date, "yyyy-MM-dd");
                    } else {
                        // 如果是纯数字
                        // 取得当前Cell的数值
                        cellValue = NumberToTextConverter.toText(cell.getNumericCellValue());

                    }
                    break;
                }
                // 如果当前Cell的Type为STRIN
                case STRING:
                    // 取得当前的Cell字符串
                    cellValue = cell.getStringCellValue().replaceAll("'", "''").trim();
                    break;
                case BLANK:
                    cellValue = null;
                    break;
                case FORMULA:
                    //cellValue=cell.getCellFormula();
                    cellValue = cell.getStringCellValue();
                    break;
                // 默认的Cell值
                default: {
                    cellValue = "";
                }
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }


}
